/*
   (C) 2007 - Michael Ocean - Boston University

  This work is a part of the larger snBench project.  Information
  can be found at: http://csr.bu.edu/snbench

  This program is free software; you can redistribute it and/or
  modify it under the terms of Version 2 of the GNU General Public 
  License.
  
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package STEPVisualizer;

import http.RawResult;
import http.Status;

import java.applet.AppletContext;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import javax.swing.ButtonGroup;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

import stepide.STEPVisualizer.JStepPanel;
import stepide.STEPVisualizer.JStepPanelEventListener;
import stepide.STEPVisualizer.JStepPanel.FakeStepNode;

public class Visualizer extends JApplet implements JStepPanelEventListener{
    /**
	 *
	 */
	private static final long serialVersionUID = 8414178008098663911L;
	/**
	 * 
	 */
	
	// needed to nav a browser window to a URL
    public AppletContext ac;
    public JRadioButton jvals;
    public JRadioButton jmeta;
        
    private static String SXEHost = null;
    private static String STEPFile = null;

    
    private static final Dimension DEFAULT_SIZE = new Dimension( 800, 600 );

    private JStepPanel stepPanel = null;
    
    public void stop() {
        System.err.println("stopping... ");
        //Node.DeRegisterAllIDs();
    }
    
    private step.Graph popGraphFromXML()
    {
    	step.Graph stepg = null;
		URI uTarget;
		try {
			uTarget = new URI(SXEHost + "/snbench/sxe/graph/");
			RawResult rr = http.Client.GET_raw(uTarget);
			
    		System.out.println("Parsing STEP XML");
    		stepg = step.parse.Parser.Parse(new String(rr.getContents()),false);
    		System.out.println("Parsed STEP XML");		

    		System.out.println(stepg.Serialize());
    		
    		System.out.println(stepg.GetNodes());
    		
    		
    		try{
    			//stepg.ResolveSplices();
    		}catch(Exception e){ e.printStackTrace(); }
    		//System.out.println("Resolved splices in STEP XML");		

		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Status e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return stepg;
    }

    private step.Graph popGraphFromFile()
    {
    	step.Graph stepg = null;
    	//java.io.File f = new java.io.File("ptz-security-feed.step.xml");
    	java.io.File f = new java.io.File(STEPFile);
    	
		if(!f.exists()){
			System.err.println("STEP file '" + f.getName() + "' does not exist.");
			return null;
		}
				
		System.out.println("Parsing STEP file '" + f.getName() + "'.");
		stepg = step.parse.Parser.Parse(f,false);
		try{
			//stepg.ResolveSplices();
		}catch(Exception e){ e.printStackTrace(); }
		
		System.out.println("Parsed STEP file '" + f.getName() + "'.");		

		return stepg;
    }
    
    /**
     * @see java.applet.Applet#init().
     */
    public void init(  ) {        
    	
    	System.err.println("Applet is running");
    	
    	this.ac = this.getAppletContext();
        jvals = new JRadioButton("data");
        jmeta = new JRadioButton("info");

    	// get applet parameters
    	String strTmp = getParameter("SXEHOST");
    	if(strTmp == null){
    		SXEHost = "http://localhost:8080";
    		System.err.println("Error -- SXEHOST param not found, using default.");
    	}
    	else{
    		SXEHost = strTmp;
    		System.err.println("SXEHOST found, using " + SXEHost);
    	}
    	
    	strTmp = getParameter("STEPFILENAME");
    	if(strTmp != null){
    		STEPFile = strTmp;
    	}
    	
    	String strWidth = getParameter("width");
    	String strHeight = getParameter("height");
    	Dimension SIZE = DEFAULT_SIZE;
    	if((strWidth != null) && (strHeight != null))
    		SIZE = new Dimension(Integer.valueOf(strWidth),Integer.valueOf(strHeight));
    	
    
    	step.Graph stepg = null;
        if(STEPFile == null){
	        stepg = popGraphFromXML();
        	if(stepg == null){
	        	System.err.println("Could not load the STEP (from SXE) into the graph");
	        	return;
	        }
        }
        else{
        	stepg = popGraphFromFile();
        	if(stepg==null){
	        	System.err.println("Could not load the STEP file into the graph");
	        	return;
	        }
        }
    
        stepPanel = new JStepPanel(stepg);

        stepPanel.addStepPanelEventListener(this);
        
        getContentPane().setLayout(new BorderLayout());
        getContentPane(  ).add( stepPanel, BorderLayout.CENTER );
        
        // create a panel containing a radio list for determining whether we show
        // meta data about a node, or the value of the node
        JPanel jp = new JPanel(new GridLayout(1,0));
        jp.add(new JLabel("  Show:"));
        jmeta.setSelected(true);
        ButtonGroup jbg = new ButtonGroup();
        jbg.add(jvals);
        jbg.add(jmeta);
        jp.add(jvals);
        jp.add(jmeta);
        
        JButton jbtnZoomIn = new JButton("Zoom in");
        JButton jbtnZoomOut = new JButton("Zoom out");
        jbtnZoomIn.addActionListener(new ActionListener() {
		
			public void actionPerformed(ActionEvent e) {
				stepPanel.Zoom(1);
			}
		
		});
        
        jbtnZoomOut.addActionListener(new ActionListener() {
    		
			public void actionPerformed(ActionEvent e) {
				stepPanel.Zoom(-1);
			}
		
		});

        jp.add(jbtnZoomIn);
        jp.add(jbtnZoomOut);
        
        getContentPane(  ).add( jp, BorderLayout.NORTH );
        
        resize( SIZE );
    }

/**
 * @return the currently selected radio button's respective URL
 */
protected String getModeSelected() {
	if(jvals.isSelected())
		return "data";
	else
		return "info";
}

public void CanvasDoubleClicked(int x, int y) {
	// TODO Auto-generated method stub
	
}

public void CanvasLeftClicked(int x, int y) {
	// TODO Auto-generated method stub
	
}

public void CanvasRightClicked(int x, int y) {
	// TODO Auto-generated method stub
	
}

public void EdgeDoubleClicked(FakeStepNode src, FakeStepNode dst, int x, int y) {
	// TODO Auto-generated method stub
	
}

public void EdgeLeftClicked(FakeStepNode src, FakeStepNode dst, int x, int y) {
	// TODO Auto-generated method stub
	
}

public void EdgeRightClicked(FakeStepNode src, FakeStepNode dst, int x, int y) {
	// TODO Auto-generated method stub
	
}

public void NodeDoubleClicked(FakeStepNode node, int x, int y) {
	// TODO Auto-generated method stub
	
}

public void NodeLeftClicked(FakeStepNode node, int x, int y) {
	String sLink = SXEHost + "/snbench/sxe/node/" + node.getNode().GetID() + "/" + getModeSelected() ;
	System.out.println(sLink);
	URL uLink;
	try {
		uLink = new URL(sLink);						
		ac.showDocument(uLink, "_values");

	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
}

public void NodeRightClicked(FakeStepNode node, int x, int y) {
	// TODO Auto-generated method stub
	
}

}